import React, { Fragment } from 'react'
import {
  View,
  StyleSheet,
  Keyboard,
  Text,
  TextInput,
  FlatList
} from 'react-native'
import { KeyboardAwareScrollView } from 'react-native-keyboard-aware-scroll-view'
import { ScaleS, ScaleT, ONE_PIXEL } from 'src/utils/ScreenUtil'
import BasePage from 'src/pageP/base/base-page/index'
import NextButton from 'src/components/button/NextButton'
import { CommonToast, ShowLoading, DismissLoading } from 'src/utils/ToastUtil'
import { companyListByKeyword, companyExist } from 'src/utils/RequestAPI'
import CustomButton from 'src/components/button/CustomButton'
import { isEmptyObjectFn } from 'src/utils/JSTypeUtil'

const debounce = require('lodash/debounce')

class BCompanyApplyName extends BasePage {
  constructor (props) {
    super(props)
    this.state = {
      header: {},
      companyName: '',
      textInputHeight: ScaleS(33),
      list: [],
      tianYanChaId: ''
    }
  }

  childRender () {
    const { companyName, textInputHeight, list, tianYanChaId } = this.state
    return (
      <Fragment>
        <KeyboardAwareScrollView
          style={styles.container}
          keyboardShouldPersistTaps="handled"
        >
          <TextInput
            style={[styles.textInput, { height: textInputHeight }]}
            value={companyName}
            placeholder="请输入公司全称"
            placeholderTextColor="#CCCCCC"
            selectionColor="#FED201"
            clearButtonMode="while-editing"
            onChangeText={this.onChangeText}
            onContentSizeChange={this.onContentSizeChange}
            maxLength={46}
            multiline={false}
            returnKeyType="search"
            enablesReturnKeyAutomatically={true}
          />
          <Text style={styles.descLabel}>
            *公司全称是营业执照名称/劳动合同的雇主名称/企业报销 发票抬头
          </Text>
          <View style={styles.tipView}>
            <Text style={styles.leftTip}>例：上海职初科技有限公司</Text>
            <Text style={styles.rightText}>
              {(companyName || '').length}/46
            </Text>
          </View>
          <FlatList
            style={[styles.list, list.length === 0 && styles.listHidden]}
            keyExtractor={this._keyExtractor}
            data={list}
            renderItem={this._renderItem}
            overScrollMode={'never'}
          />
        </KeyboardAwareScrollView>
        <NextButton
          style={styles.nextButton}
          title="下一步"
          enable={!!tianYanChaId}
          onPress={this._nextBtnClick}
        />
      </Fragment>
    )
  }

  _keyExtractor = (item, index) => item.id + '' || index + 'PersonCell'

  _renderItem = cell => (
    <CustomButton params={cell.item} onPress={this._clickItem}>
      <View style={styles.listItem}>
        <Text style={styles.listLabel}>{cell.item.name}</Text>
      </View>
    </CustomButton>
  )

  _clickItem = item => {
    Keyboard.dismiss()
    this.setState({
      tianYanChaId: item.id,
      companyName: item.name,
      list: []
    })
  }

  onContentSizeChange = e => {
    const {
      nativeEvent: {
        contentSize: { height }
      }
    } = e
    this.setState({
      textInputHeight: ScaleS(Math.max(height, 33))
    })
  }

  onChangeText = companyName => {
    console.log('onChangeText', companyName)
    this.setState({
      companyName,
      tianYanChaId: ''
    })
    if (!companyName) {
      return
    }
    this.throttleOnChangeText(companyName)
  }

  throttleOnChangeText = debounce(keyword => {
    console.log('onChangeTextDelay', keyword)
    companyListByKeyword({ params: { keyword } }).then(res => {
      this.setState({
        list: res.data.map(e => ({
          ...e,
          name: e.name.replace(/<(?:.|\s)*?>/g, '')
        }))
      })
    })
  }, 300)

  _nextBtnClick = () => {
    const { tianYanChaId, companyName } = this.state
    if (!tianYanChaId) {
      CommonToast(`请输入并选择有效的公司全称`)
      return
    }
    ShowLoading()
    companyExist({ params: { companyName } }).then(res => {
      if (!isEmptyObjectFn(res.data)) {
        this.props.navigation.replace('BCompanyApplyJoin', {
          companyId: res.data.companyId,
          companyName: res.data.companyName
        })
      } else {
        this.props.navigation.replace('BCompanyApplyLicence', {
          tianYanChaId,
          companyName
        })
      }
    }).finally(() => {
      DismissLoading()
    })
  }
}
export default BCompanyApplyName
const styles = StyleSheet.create({
  container: {
    flex: 1,
    marginBottom: ScaleS(90)
  },
  textInput: {
    marginTop: ScaleS(16),
    marginBottom: ScaleS(24),
    marginHorizontal: ScaleS(20),
    fontSize: ScaleT(27),
    fontWeight: '500',
    lineHeight: ScaleS(33),
    color: '#000000'
  },
  descLabel: {
    marginTop: ScaleS(8),
    marginHorizontal: ScaleS(20),
    color: '#CCCCCC',
    fontSize: ScaleT(13),
    lineHeight: ScaleS(23),
    fontWeight: '400'
  },
  tipView: {
    marginTop: ScaleS(10),
    flexDirection: 'row',
    alignItems: 'center',
    height: ScaleS(19),
    marginHorizontal: ScaleS(20)
  },
  leftTip: {
    flex: 1,
    color: '#FFC200',
    fontSize: ScaleT(14),
    fontWeight: '400'
  },
  rightText: {
    color: '#FFC200',
    fontSize: ScaleT(14),
    fontWeight: '600'
  },
  listHidden: {
    minHeight: 0,
    height: 0,
    flex: 0
  },
  list: {
    marginTop: ScaleS(-86),
    backgroundColor: '#fff',
    minHeight: ScaleS(150),
    flex: 1
  },
  listItem: {
    borderBottomWidth: ONE_PIXEL,
    borderStyle: 'solid',
    borderColor: '#EFEFEF',
    paddingVertical: ScaleS(10),
    paddingHorizontal: ScaleS(20),
    justifyContent: 'center'
  },
  listLabel: {
    color: '#666666',
    fontSize: ScaleT(16),
    lineHeight: ScaleS(30),
    fontWeight: '400'
  },
  nextButton: {
    position: 'absolute',
    bottom: ScaleS(20),
    left: ScaleS(32)
  }
})
